package com.xiaoc.bulldozer.job;


import com.xc.framework.common.job.AbstractParallelJob;
import com.xiaoc.bulldozer.common.ConfigKeys;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.dto.AwardDto;
import com.xiaoc.bulldozer.common.service.AwardService;
import com.xiaoc.bulldozer.common.service.CommonConfigService;
import com.xiaoc.bulldozer.common.service.SmtpMessageService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 红包接近过期通知 定时任务
 */

@Component
@EnableScheduling
public class AwardCloseToTimeoutInformJob extends AbstractParallelJob {

    private Logger logger = LoggerFactory.getLogger(AwardCloseToTimeoutInformJob.class);

    @Resource(name = "awardService")
    private AwardService awardService;

    @Resource(name = "smtpMessageService")
    SmtpMessageService smtpMessageService;

    @Resource(name = "commonConfigService")
    CommonConfigService commonConfigService;


    @Override
    public String getJobName() {
        return "AwardCloseToTimeoutInformJob";
    }

    /**
     * 每天的早8点到晚8点，每隔5分钟执行一次
     */
    @Override
    @Scheduled(cron = "0 0/5 8-19 * * ?")
    public void run() {
        super.run();
    }

    @Override
    public void execute() {
        sendInform();
    }


    private void sendInform() {

        // 最后一个发送消息的AwardId
        Integer awardId = awardService.getLastAwardIdSendInform(commonConfigService.getConfigValueFromDB(ConfigKeys.LAST_AWARD_ID_SEND_INFORM));

        // 过期剩余时间 单位小时
        Integer remainTime = awardService.getAwardExpiredRemainingTimeUnitHour();

        // 消息
        String msg = awardService.getAwardCloseToTimeoutMsg();

        // 消息内容是空，就不发
        if (StringUtils.isBlank(msg)) {
            return;
        }
        msg = StringUtils.replace(msg, "{hour}", remainTime.toString());

        String messageContent ;

        long current = System.currentTimeMillis();

        long timeout = remainTime * 3600000L;

        DecimalFormat df = new DecimalFormat("0.00");


        List<AwardDto> awardList = awardService.getAwardListByIdAndStatus(awardId, Constant.ENABLE);

        Integer lastAwardId = awardId;

        if (CollectionUtils.isNotEmpty(awardList)) {

            for (AwardDto awardDto : awardList) {

                if (awardDto.getEndTime() - current <= timeout && StringUtils.isNotBlank(awardDto.getPhoneNumber())) {

                    lastAwardId = awardDto.getId();

                    String fee = df.format((float) awardDto.getFee() / 100);

                    messageContent = StringUtils.replace(msg, "{fee}", fee);

                    try {
                        smtpMessageService.sendMessageSaveLog(awardDto.getPhoneNumber(), messageContent,Constant.CODE_TYPE.AWARD_EXPIRE);
                    } catch (Exception e) {
                        logger.error("sendInform error", e);
                    }

                }
            }

            if (lastAwardId > awardId) {
                commonConfigService.updateConfigValue(ConfigKeys.LAST_AWARD_ID_SEND_INFORM, lastAwardId + "");
            }


        }
    }
}
